import React, { Component } from "react";

export default class FormCom extends Component {
  //1. 声明状态
  state = {
    user: '',
    pass: '',
    repass: ''
  }
  //3. input 元素的 onChange 事件回调
  save = (e) => {
    //获取当前input对应的状态名
    let name = e.target.name;
    //更新状态
    this.setState({
      [name]: e.target.value 
    })
  }

  render() {
    return (
      <div>
        <h2>登录</h2>
        <form action="">
          <hr />
          {/* 2. 使用状态设置表单元素的值   受控: 受状态的控制 */}  
          用户名: <input name='user' type="text" value={this.state.user} onChange={this.save} />
          <br />
          密码: <input name='pass' type="text" value={this.state.pass} onChange={this.save} />
          <br />
          确认密码: <input name="repass" type="text" value={this.state.repass} onChange={this.save} />
          <hr />
          <button onClick={this.login}>登录</button>
          <button type="button" onClick={this.reset}>重置</button>
        </form>
      </div>
    );
  }

  //登录的单击事件
  login = (e) => {
    e.preventDefault();
    //获取表单元素的值
    console.log(`用户名: ${this.state.user} 密码: ${this.state.pass}`)
  };

  //表单重置
  reset = (e) => {
    e.preventDefault();
    //更新状态
    this.setState({
      user: '',
      pass: ''
    })
  }

}
